﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace Zoomtel.Utils.Helpers
{
   public class HttpHelper
    {

       public class GetResult
        {
            public string HeadersJson { get
                {
                    if (Headers == null || Headers.Count == 0)
                    {
                        return "";
                    }
                    else
                    {
                        Dictionary<string, string> map = new Dictionary<string, string>();
                        foreach(string key in Headers.Keys)
                        {
                            map.Add(key, Headers[key]);
                        }

                        return Newtonsoft.Json.JsonConvert.SerializeObject(map);
                    }

                } }

            public WebHeaderCollection Headers { get; set; }
            public string StatusCode{ get; set; }
            public string Result { get; set; }
        }

        #region URL请求数据

        /// <summary>
        /// HTTP POST方式请求数据
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="param">POST的数据</param>
        /// <returns></returns>
        public static GetResult HttpPostGetResult(string url, string param)
        {
            GetResult result = new GetResult();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            HttpWebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse() as HttpWebResponse;

                if (response != null)
                {
                 result.Headers=   response.Headers;
                    result.StatusCode = Convert.ToInt32( response.StatusCode).ToString();
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                    result.Result = responseStr;

                }
            }
            catch (WebException ee)
            {
                using (WebResponse response2 = ee.Response)
                {

                    HttpWebResponse httpErrorResponse = (HttpWebResponse)response2;

                    if (httpErrorResponse != null)
                    {
                        result.Headers = httpErrorResponse.Headers;
                        result.StatusCode= Convert.ToInt32(httpErrorResponse.StatusCode).ToString();
                        using (Stream data = response2.GetResponseStream())

                        using (var reader = new StreamReader(data))
                        {

                           result.Result = reader.ReadToEnd();

                        }
                    }

                }
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }
            return result;
        }
      static  MemoryStream StreamToMemoryStream(Stream instream)
        {
            MemoryStream outstream = new MemoryStream();
            const int bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
            {
                outstream.Write(buffer, 0, count);
            }
            return outstream;
        }

        public static string HttpPostBase64(string url, string param, string contentType = "application/x-www-form-urlencoded")
        {
            // content-type: application/json;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.Accept = "*/*";
            request.Timeout = 15000;
            //request.TransferEncoding
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            HttpWebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse() as HttpWebResponse;

                if (response != null)
                {

                    var stream = response.GetResponseStream();


                    var ms = StreamToMemoryStream(stream);
                    ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream

                    byte[] bytes = new byte[buffsize];

                    ms.Read(bytes, 0, buffsize);
                    ms.Flush();
                    ms.Close();
                    stream.Flush();
                    stream.Close();


                    string str = Convert.ToBase64String(bytes);
                    return str;



                    //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    //responseStr = reader.ReadToEnd();
                    //reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;

        }

        /// <summary>
        /// HTTP POST方式请求数据
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="param">POST的数据</param>
        /// <returns></returns>
        public static string HttpPost(string url, string param,string contentType= "application/x-www-form-urlencoded")
        {
            // content-type: application/json;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.Accept = "*/*";
            request.Timeout = 15000;
            //request.TransferEncoding
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            HttpWebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse() as HttpWebResponse;
          
                if (response != null)
                {


                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }

        /// <summary>
        /// HTTP GET方式请求数据.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }

   
        #endregion
    }
}
